#!/usr/bin/php
<?php

require_once('Zabbix_Sensor.php');
require_once('Zabbix_Sensor_Apache.php');
require_once('Zabbix_Sensor_Mysql.php');

class Zabbix {

    protected $_options = array();


    protected function __construct() {
        $this->prepareCommand();
    }

    public static function instance() {
        return new self();
    }

    protected function parseOption($option) {
        $result = null;
        $pattern = '#^--([^=]+)=(.*)$#i';
        if (preg_match($pattern, $option, $m) === 1) {

            $name = $m[1];
            $value = $m[2];

            $this->_options[$name] = $value;
        }
        return $result;
    }

    protected function prepareCommand() {
        global $argv;
        $options = array_slice($argv, 1);
        foreach($options as $option) {
            $this->parseOption($option);
        }
    }

    protected function getOption($name, $default = null) {
        $result = $default;
        if (array_key_exists($name, $this->_options)) {
            $result = $this->_options[$name];
        }
        return $result;
    }

    protected function getOptions() {
        return $this->_options;
    }

    protected function createSensor($sensorName) {
        $sensor = new $sensorName($host);
        return $sensor;
    }

    protected function prepareSensor($sensor) {
        // Initialize sensor
        $sensor->init();

        // Check key
        $key = $this->getOption('key');

        // Getting key
        if ($key !== null) {
            echo $sensor->getAttribute($key);
        } else {
            $attributes = $sensor->getAttributes();
            foreach($attributes as $name => $value) {
                echo $name . '=' .$value . PHP_EOL;
            }
        }
    }

    /**
     */
    public function run() {

        // Show command
        $verbose = $this->getOption('verbose');
        if ($verbose !== null) {
            foreach($this->_options as $name => $value) {
                echo '  ' . $name . ' = ' . $value . PHP_EOL;
            }
        }

        $sensorName = 'Zabbix' . '_' . 'Sensor' . '_' . $this->getOption('sensor', 'Mysql');

        $sensor = $this->createSensor($sensorName);
        if ($sensor !== null) {

            // Save parameters
            $options = $this->getOptions();
            $sensor->setOptions($options);

            // Prepare sensor
            $this->prepareSensor($sensor);
        }
    }

}

// Start
Zabbix::instance()->run();
